/**
 * 注册
 */
import { omit } from "lodash";
import { checkPhone } from "../../../model/service/account/phone";
import { registerService } from "../../../model/service/account/register";
import codeUtil from "../../../util/code/codeUtil";
import { validatePhnoeNubmer, UUID36 } from "../../../util/index";
import { hashPassword } from "../../../util/security";

export default async function register(
  ctx: Context,
  next: Next
): Promise<void> {
  const { body } = ctx.request;
  const { phoneNumber, code } = body;

  const result = await checkPhone(phoneNumber);

  // 验证码不正确
  if (result.length !== 0) {
    ctx.api.fail(-1, "该手机号已被注册");
  } else if (!codeUtil.verifyCode(phoneNumber, code)) {
    ctx.api.fail(-1, "验证码错误");
  } else if (!validatePhnoeNubmer(phoneNumber)) {
    ctx.api.fail(-1, "不合法的手机号");
  } else {
    const userInfo = omit(body, ['code']);
    userInfo.uid = UUID36(10);
    userInfo.password = hashPassword(userInfo.password);
    // 这里不应该返回全部的数据，防止隐私泄漏
    const responseData = await registerService(userInfo);
    ctx.api.success({ uid: responseData.uid }, "sucess");
  }

  return next();
}
